package org.jeecg.modules.system.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserPlan;
import org.jeecg.modules.system.service.ISysUserPlanService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: sys_user_plan
 * @Author: jeecg-boot
 * @Date:   2022-10-13
 * @Version: V1.0
 */
@Api(tags="工作计划接口")
@RestController
@RequestMapping("/system/sysUserPlan")
@Slf4j
public class SysUserPlanController extends JeecgController<SysUserPlan, ISysUserPlanService> {
	@Autowired
	private ISysUserPlanService sysUserPlanService;	@Autowired
	private ISysUserService sysUserService;
	
	/**
	 * 分页列表查询
	 *
	 * @param sysUserPlan
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "工作计划-分页列表查询")
	@ApiOperation(value="工作计划-分页列表查询", notes="工作计划-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<SysUserPlan>> queryPageList(SysUserPlan sysUserPlan,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SysUserPlan> queryWrapper = QueryGenerator.initQueryWrapper(sysUserPlan, req.getParameterMap());

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		/*SysRole role = sysUserRoleService.getUserRole(sysUser.getId());
		if ("distributor".equals(role.getRoleCode())) {
			List<String> userIds = getDistributor(sysUser.getId());
			userIds = CollectionUtils.isEmpty(userIds) ? Arrays.asList("eqwewq") : userIds;
			queryWrapper.in("id", userIds);
		} else {
			queryWrapper.eq("create_by", sysUser.getUsername());
		}
*/

		queryWrapper.lambda().eq(SysUserPlan::getUserid,sysUser.getId());

		Page<SysUserPlan> page = new Page<SysUserPlan>(pageNo, pageSize);
		IPage<SysUserPlan> pageList = sysUserPlanService.page(page, queryWrapper);




		pageList.getRecords().stream().forEach(e->{e.setUserName(sysUserService.getById(e.getUserid()).getRealname());});
		return Result.OK(pageList);
	}
	
	@ApiOperation(value="未完成的工作计划查询", notes="未完成的工作计划查询")
	@GetMapping(value = "/undo/list")
	public Result<List<SysUserPlan>> undo(@RequestParam(value = "userId",required = false) String userId) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		LambdaQueryWrapper<SysUserPlan> queryWrapper = new LambdaQueryWrapper();
		if(StringUtils.isEmpty(userId)){
			queryWrapper.eq(SysUserPlan::getUserid,sysUser.getId());
		}else {
			queryWrapper.eq(SysUserPlan::getUserid,userId);
		}
		queryWrapper.eq(SysUserPlan::getStatus,"0");
		queryWrapper.orderBy(true,false,SysUserPlan::getCreateTime);
		List<SysUserPlan> list = sysUserPlanService.list(queryWrapper);
		return Result.OK(list);
	}
	@ApiOperation(value="已完成的工作计划查询", notes="已完成的工作计划查询")
	@GetMapping(value = "/done/list")
	public Result<List<SysUserPlan>> done(@RequestParam(value = "userId",required = false) String userId) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		LambdaQueryWrapper<SysUserPlan> queryWrapper = new LambdaQueryWrapper();
		if(StringUtils.isEmpty(userId)){
			queryWrapper.eq(SysUserPlan::getUserid,sysUser.getId());
		}else {
			queryWrapper.eq(SysUserPlan::getUserid,userId);
		}
		queryWrapper.eq(SysUserPlan::getStatus,"1");
		queryWrapper.orderBy(true,false,SysUserPlan::getCreateTime);
		queryWrapper.last("limit 5");
		return Result.OK(sysUserPlanService.list(queryWrapper));
	}
	
	/**
	 *   添加
	 *
	 * @param sysUserPlan
	 * @return
	 */
	@AutoLog(value = "工作计划-添加")
	@ApiOperation(value="工作计划-添加", notes="工作计划-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:sys_user_plan:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody SysUserPlan sysUserPlan) {

		if (org.apache.commons.lang.StringUtils.isBlank(sysUserPlan.getUserid())) {
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			sysUserPlan.setUserid(sysUser.getId());
		}
		sysUserPlan.setStatus("0");
		sysUserPlanService.save(sysUserPlan);
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SysUser::getUsername,sysUserPlan.getCreateBy());
		sysUserPlan.setCreateByName(sysUserService.getOne(queryWrapper).getRealname());
		sysUserPlanService.updateById(sysUserPlan);

		return Result.OK("添加成功！");
	}
	
	@PostMapping(value = "/{id}/{status}")
	public Result<String> status(@PathVariable("id") String id,@PathVariable("status") String status) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		SysUserPlan sysUserPlan = sysUserPlanService.getById(id);
		if(sysUserPlan != null){
			sysUserPlan.setStatus(status);
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			sysUserPlan.setEndDateAct(sf.format(new Date()));
			sysUserPlanService.updateById(sysUserPlan);
		}
		return Result.OK("添加成功！");
	}
	@PostMapping(value = "/date/{id}/{date}")
	public Result<String> date(@PathVariable("id") String id,@PathVariable("date") String date) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		SysUserPlan sysUserPlan = sysUserPlanService.getById(id);
		if(sysUserPlan != null){
			sysUserPlan.setEndDate(date);
			sysUserPlanService.updateById(sysUserPlan);
		}
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param sysUserPlan
	 * @return
	 */
	@AutoLog(value = "工作计划-编辑")
	@ApiOperation(value="工作计划-编辑", notes="工作计划-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:sys_user_plan:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody SysUserPlan sysUserPlan) {
		sysUserPlanService.updateById(sysUserPlan);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "工作计划-通过id删除")
	@ApiOperation(value="工作计划-通过id删除", notes="工作计划-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:sys_user_plan:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		sysUserPlanService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "工作计划-批量删除")
	@ApiOperation(value="工作计划-批量删除", notes="工作计划-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:sys_user_plan:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.sysUserPlanService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "工作计划-通过id查询")
	@ApiOperation(value="工作计划-通过id查询", notes="工作计划-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<SysUserPlan> queryById(@RequestParam(name="id",required=true) String id) {
		SysUserPlan sysUserPlan = sysUserPlanService.getById(id);
		if(sysUserPlan==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(sysUserPlan);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param sysUserPlan
    */
    //@RequiresPermissions("org.jeecg.modules.demo:sys_user_plan:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysUserPlan sysUserPlan) {
        return super.exportXls(request, sysUserPlan, SysUserPlan.class, "sys_user_plan");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("工作计划:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysUserPlan.class);
    }

}
